/**
 * @param {number[]} tasks
 * @param {number} space
 * @return {number}
 */
 var taskSchedulerII = function(tasks, space) {
    let flag = {};
    let res = 0;
    for(let i = 0; i < tasks.length; i++){
        if(flag[tasks[i]] == undefined){
            res++;
        }else{
            let ind = res - flag[tasks[i]];
            if(ind >= space){
                res++;
            }else{
                res += space - ind + 1;
            }
        }
        flag[tasks[i]] = res;
    }
    return res;
};